package com.jiepos.mpos.inter.message.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.appInfM.service.OrganizationService;
import com.jiepos.mpos.biz.customer.service.AppCustomerInfoService;
import com.jiepos.mpos.biz.operationlog.service.SmsCodeFlowService;
import com.jiepos.mpos.common.constant.RspCodeConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.entity.App_Custom_InfEntity;
import com.jiepos.mpos.common.entity.GpsEntity;
import com.jiepos.mpos.core.util.RSACoder;
import com.jiepos.mpos.core.util.StringUtils;

@Service
public class RandService {

	private final Logger log = LoggerFactory.getLogger(RandService.class);

	@Autowired
	private OrganizationService organizationService;

	@Autowired
	private IPhoneMessageService iPhoneMessageService;

	@Autowired
	private SmsCodeFlowService smsCodeFlowService;

	@Autowired
	private AppCustomerInfoService appCustomerInfoService;

	/**
	 * 获取验证码
	 * @param phone 手机号
	 * @param type 验证码类型
	 * @param gpsEntity App接口调用 使用此参数 否则传null
	 * @param sup_custom_uuid H5调用 使用此参数 否则传null
	 * @param dataMap 预留方案；
	 * @return
	 */
	public Map getRand(String phone,String type,GpsEntity gpsEntity,String sup_custom_uuid,Map dataMap){
		Map<String,Object> resMap = new HashMap<>();
		resMap.put(SystemConstant.RSP_CODE,SystemConstant.RSPCODE_SUCCESS);
		resMap.put(SystemConstant.RSP_DATAMAP,new HashMap<>());
		//验证码发送过频校验
		Date lastRandSendTime = smsCodeFlowService.getLastRandSendTime(type, phone);
		if(lastRandSendTime != null){
			//60秒内发送过验证码
			long interval = (new Date().getTime() - lastRandSendTime.getTime()) / 1000 ;
			if(interval < 30){
				//提示一分钟后再发送
				resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200111);
				resMap.put(SystemConstant.RSP_MSG,"操作频繁,请60秒后再试");
				return resMap;
			}else if(interval < 60){
				//提示30秒后再发送
				resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200111);
				resMap.put(SystemConstant.RSP_MSG,"操作频繁,请30秒后再试");
				return resMap;
			}else{
				//可以直接发送了
			}

		}
		//分类表查询机构app信息
		//获取机构App设置信息
		Map<String, Object> insAppInfo = null;
		if(gpsEntity != null){ //app接口调用
			//通过appid查询
			insAppInfo = organizationService.getInsAppInfoByAppid(gpsEntity.getAppType(), gpsEntity.getApp_id());
		}else if(!StringUtils.isBlank(sup_custom_uuid)){ //H5调用
			//根据根据推荐人会员信息得到推荐人信息
			App_Custom_InfEntity customInf = appCustomerInfoService.getCustomByCustomUUID(sup_custom_uuid);
			//未查到对应用户信息
			if(customInf == null || StringUtils.isBlank(customInf.getCustom_uuid())){
				log.info("推荐人不正确");
				resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200008);
				return resMap;
			}
			//通过机构uuid查询
			insAppInfo = organizationService.getInsAppInfoByInsUUID(customInf.getIns_uuid());
		}else{

		}
		//判断查询结果
		if(insAppInfo != null && insAppInfo.get("MSG_SIGN") !=null && insAppInfo.get("SMS_USERNAME") !=null
				&& insAppInfo.get("SMS_PASSWORD") !=null){
			//短信通道 登录名
			String name = insAppInfo.get("SMS_USERNAME").toString();
			// 短信通道密码 解密
			String pwd = insAppInfo.get("SMS_PASSWORD").toString();
			byte[] rsaPrivateKeys = new byte[0];
			try {
				rsaPrivateKeys = RSACoder.decryptByPrivateKey(RSACoder.decryptBASE64(pwd), SystemConstant.PRI_KEY_STR);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("RSA解密异常");
				resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200102);
				return resMap;
			}
			pwd = RSACoder.encryptBASE64(rsaPrivateKeys);
			//机构码
			String insCd = null;
			if(insAppInfo.get("INS_CD") != null){
				insCd = insAppInfo.get("INS_CD").toString();
			}
			//生成短信验证码
			String random = StringUtils.createRandom(true, 6);
			log.info("生成验证码："+random);
			//短信内容
			StringBuffer content = new StringBuffer();
			content.append(insAppInfo.get("MSG_SIGN").toString());
			content.append("短信验证码"+random+",5分钟内有效");
			//调用短信发送接口
			Map sendResultMap = iPhoneMessageService.sendMessage(name, pwd, phone, content.toString(), insCd);
			/*
				响应体
				0 = {HashMap$Node@1491} "ReqMsg" -> "提交成功"
				1 = {HashMap$Node@1492} "ReqId" -> "171013151023103010100010"
				2 = {HashMap$Node@1493} "ReqCode" -> "00"
			 */
			if(sendResultMap != null){
				//记录短信验证码发送记录
				smsCodeFlowService.saveSmsCodeFlow(random,type,StringUtils.objToString(sendResultMap.get("ReqCode"))
						,StringUtils.objToString(sendResultMap.get("ReqMsg")),StringUtils.objToString(insAppInfo.get("INS_UUID")),phone);
				if(SystemConstant.RSPCODE_SUCCESS.equals(sendResultMap.get("ReqCode").toString())){
					log.info("验证码发送成功");
					resMap.put(SystemConstant.RSP_MSG,"验证码发送成功");
					return resMap;
				}else{
					log.info("验证码发送失败："+sendResultMap.get("ReqMsg").toString());
					resMap.put(SystemConstant.RSP_CODE,SystemConstant.RSPCODE_ERROR);
					resMap.put(SystemConstant.RSP_MSG,sendResultMap.get("ReqMsg").toString());
					return resMap;
				}
			}else{
				//短信通道无响应
				log.info("验证码发送失败：通道无响应");
				resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200101);
				return resMap;
			}
		}else{
			log.info("验证码发送失败：信息缺失");
			//未查到相关机构app信息；
			resMap.put(SystemConstant.RSP_CODE,RspCodeConstant.RSPCODE_200100);
			return resMap;
		}

	}
}
